package fairygui.editor.publish.exporter
{
   import fairygui.editor.publish.PublishStep;
   import fairygui.editor.settings.GlobalPublishSettings;
   import fairygui.editor.utils.UtilsFile;
   import fairygui.editor.utils.UtilsStr;
   import fairygui.editor.utils.zip.ZipArchive;
   import fairygui.editor.utils.zip.ZipConstants;
   import flash.filesystem.File;
   import flash.utils.ByteArray;
   
   public class UnityExporter extends PublishStep
   {
       
      
      public function UnityExporter()
      {
         super();
      }
      
      private static function checkUnityVersion55(param1:File) : Boolean
      {
         var unityFolder:File = null;
         var verFile:File = null;
         var fcontent:String = null;
         var arr:Array = null;
         var str:String = null;
         var file:File = param1;
         var isUnity55:Boolean = false;
         try
         {
            unityFolder = file;
            while(unityFolder.exists)
            {
               if(unityFolder.name == "Assets")
               {
                  unityFolder = unityFolder.parent.resolvePath("ProjectSettings");
                  if(unityFolder == null)
                  {
                     break;
                  }
                  verFile = unityFolder.resolvePath("ProjectVersion.txt");
                  if(verFile.exists)
                  {
                     fcontent = UtilsFile.loadString(verFile);
                     arr = fcontent.split("\n");
                     for each(str in arr)
                     {
                        if(UtilsStr.startsWith(str,"m_EditorVersion"))
                        {
                           str = str.substr(17);
                           arr = str.split(".");
                           if(int(arr[0]) >= 5 && int(arr[1]) >= 5)
                           {
                              isUnity55 = true;
                           }
                           break;
                        }
                     }
                  }
                  break;
               }
               unityFolder = unityFolder.parent;
               if(unityFolder == null)
               {
                  break;
               }
            }
         }
         catch(err:Error)
         {
         }
         return isUnity55;
      }
      
      override public function run() : void
      {
         var fn:String = null;
         var descData:* = undefined;
         var str:String = null;
         var ba:ByteArray = null;
         var gsettings:GlobalPublishSettings = null;
         var zip:ZipArchive = null;
         var files:Array = null;
         var checkStr:String = null;
         var i:int = 0;
         var textureFormat:int = 0;
         var imageMeta:String = null;
         var nn:String = null;
         var nnn:String = null;
         var pos:int = 0;
         var file:File = null;
         var metaFile:File = null;
         var descFile:File = new File(publishData.filePath + "/" + publishData.fileName + "." + publishData.fileExtention);
         var resPrefix:String = publishData.filePath + "/" + publishData.fileName + "@";
         var output:Array = [];
         var toSort:Array = [];
         for(fn in publishData.outputDesc)
         {
            toSort.push(fn);
         }
         toSort.sort();
         gsettings = publishData._project.settingsCenter.publish;
         if(gsettings.unityDataFormat == 1)
         {
            zip = new ZipArchive();
            for each(fn in toSort)
            {
               descData = publishData.outputDesc[fn];
               if(descData is XML)
               {
                  str = (descData as XML).toXMLString();
               }
               else
               {
                  str = String(descData);
               }
               zip.addFileFromString(fn,str);
            }
            UtilsFile.saveBytes(descFile,zip.output(ZipConstants.STORED));
         }
         else
         {
            for each(fn in toSort)
            {
               descData = publishData.outputDesc[fn];
               if(descData is XML)
               {
                  str = (descData as XML).toXMLString();
               }
               else
               {
                  str = String(descData);
               }
               output.push(fn);
               output.push("|");
               output.push("" + str.length);
               output.push("|");
               output.push(str);
            }
            ba = new ByteArray();
            ba.writeUTFBytes(output.join(""));
            UtilsFile.saveBytes(descFile,ba);
         }
         if(!publishData.exportDescOnly)
         {
            files = descFile.parent.getDirectoryListing();
            checkStr = publishData.fileName + "@";
            i = 0;
            for(; i < files.length; i++)
            {
               nn = files[i].name;
               if(UtilsStr.startsWith(nn,checkStr))
               {
                  if(UtilsStr.endsWith(nn,".meta"))
                  {
                     nnn = nn.substr(0,nn.length - 5);
                     pos = nnn.indexOf("@");
                     if(pos != -1)
                     {
                        nnn = nnn.substr(pos + 1);
                     }
                     if(publishData.outputRes[nnn] || nnn == "sprites.bytes" || nnn == "hittest.bytes" && publishData.hitTestData.length > 0)
                     {
                        continue;
                     }
                  }
                  try
                  {
                     files[i].deleteFile();
                  }
                  catch(err:Error)
                  {
                     stepCallback.msgs.length = 0;
                     stepCallback.addMsg("Unable to delete file \'" + nn + "\'");
                     stepCallback.callOnFailImmediately();
                     return;
                  }
                  continue;
               }
            }
            textureFormat = !!publishData.extractAlpha?-1:-3;
            imageMeta = "TextureImporter:\n" + "  mipmaps:\n" + "    enableMipMap: 0\n" + "  textureFormat: " + textureFormat + "\n" + "  maxTextureSize: 2048\n" + "  nPOTScale: 0";
            if(checkUnityVersion55(descFile))
            {
               imageMeta = imageMeta + ("\n  textureType: 0\n" + "  textureShape: 1");
            }
            for(fn in publishData.outputRes)
            {
               file = new File(resPrefix + fn);
               ba = publishData.outputRes[fn];
               UtilsFile.saveBytes(file,ba);
               if(file.extension == "jpg" || file.extension == "png")
               {
                  metaFile = new File(file.nativePath + ".meta");
                  if(!metaFile.exists)
                  {
                     try
                     {
                        UtilsFile.saveString(metaFile,imageMeta,"UTF-8");
                     }
                     catch(err:Error)
                     {
                        continue;
                     }
                  }
               }
            }
            file = new File(resPrefix + "sprites.bytes");
            ba = new ByteArray();
            ba.writeUTFBytes(publishData.sprites);
            UtilsFile.saveBytes(file,ba);
            if(publishData.hitTestData.length > 0)
            {
               file = new File(resPrefix + "hittest.bytes");
               UtilsFile.saveBytes(file,publishData.hitTestData);
            }
         }
         stepCallback.callOnSuccess();
      }
   }
}
